# -*- coding: utf-8 -*-
from __future__ import unicode_literals
class WordReader(object):
    """Reads .docx and .doc-files (the latter with support from antiword) and presents a slightly easier API for dealing with them."""

    def read(self, wordfile, workdir=None):
        """Read the file"""
        pass

    def word_to_html(indoc, outhtml):
        """Converts a word document to a HTML document by remote
        controlling Microsoft Word to open and save the doc as HTML (so
        this function only works on Win32 with Office 2003 installed)"""
        indoc = os.path.join(os.getcwd(), indoc.replace("/", os.path.sep))
        outhtml = os.path.join(os.getcwd(), outhtml.replace("/", os.path.sep))
        display_indoc = indoc[len(os.getcwd()):].replace(os.path.sep, "/")
        display_outhtml = outhtml[len(os.getcwd()):].replace(os.path.sep, "/")
        # print "Ensuring dir for %r" % outhtml
        ensure_dir(outhtml)
        if not os.path.exists(indoc):
            print(("indoc %s does not exists (seriously)" % indoc))
        if os.path.exists(outhtml):
            # if self.verbose: print "local file %s exists, not doing Word->HTML conversion" % display_outhtml
            return
        #if os.path.exists(outhtml + ".err.log"):
        #    print "Word->HTML conversion for local file %s has failed, not re-trying"% display_outhtml
        #    return
        from win32com.client import Dispatch
        import pywintypes
        wordapp = Dispatch("Word.Application")
        if wordapp is None:
            print("Couldn't start word")
            return
        # print "word_to_html: %s to %s" % (indoc,outhtml)
        try:
            wordapp.Documents.Open(indoc)
            wordapp.Visible = False
            doc = wordapp.ActiveDocument
            doc.SaveAs(outhtml, 10)  # 10 = filtered HTML output
            doc.Close()
            doc = None
            wordapp.Quit
        except pywintypes.com_error as e:
            print(("Warning: could not convert %s" % indoc))
            print((e[2][2]))
            errlog = open(outhtml + ".err.log", "w")
            errlog.write("%s:\n%s" % (indoc, e))
